package service

import (
	"errors"
	"fmt"
	"gin-learn/global"
	"gin-learn/model"
	"gin-learn/model/request"
	"gin-learn/utils"

	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
)

func Login(u *model.SysUser) (err error, userInter *model.SysUser) {
	var user model.SysUser
	u.Password = utils.MD5V(u.Password)
	err = global.G_DB.Where("username = ? AND password = ?", u.Username, u.Password).First(&user).Error
	fmt.Println(&user)
	return err, &user
}

func Register(u model.SysUser) (err error, resUser model.SysUser) {
	var user model.SysUser
	// 判断用户名是否注册
	if !errors.Is(global.G_DB.Where("username = ?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) {
		return errors.New("用户名已注册"), resUser
	}
	// 否则 附加uuid 密码md5简单加密 注册
	u.Password = utils.MD5V(u.Password)
	u.UUID = uuid.NewV4()
	err = global.G_DB.Create(&u).Error
	return err, u
}

func ChangePassword(u *model.SysUser, newPassword string) (err error, resUser model.SysUser) {
	var user model.SysUser
	u.Password = utils.MD5V(u.Password)
	err = global.G_DB.Where("username = > AND password = ?", u.Username, u.Password).First(&user).Update("password", utils.MD5V(newPassword)).Error
	return err, user
}

// 分页获取数据
func GetUserInfoList(info request.PageInfo) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.G_DB.Model(&model.SysUser{})
	var userList []model.SysUser
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Preload("Authority").Find(&userList).Error
	return err, userList, total
}

// 设置一个用户的权限
func SetUserAuthority(uuid uuid.UUID, authorityId string) (err error) {
	err = global.G_DB.Where("uuid = ?", uuid).First(&model.SysUser{}).Update("authority_id", authorityId).Error
	return err
}

// 删除用户
func DeleteUser(id float64) (err error) {
	var u model.SysUser
	err = global.G_DB.Where("id = ?", id).Delete(&u).Error
	return err
}

// 设置用户信息
func SetUserInfo(reqUser model.SysUser) (err error, user model.SysUser) {
	err = global.G_DB.Updates(&reqUser).Error
	return err, reqUser
}

// 通过id获取用户信息
func FindUserByID(id int) (err error, user *model.SysUser) {
	var u model.SysUser
	if err = global.G_DB.Where("`id` = ?", id).First(&u).Error; err != nil {
		return errors.New("用户不存在"), &u
	}
	return nil, &u
}

// 通过uuid获取用户信息
func FindUserByUUID(uuid string) (err error, user *model.SysUser) {
	var u model.SysUser
	if err = global.G_DB.Where("`uuid` = ?", uuid).First(&u).Error; err != nil {
		return errors.New("用户不存在"), &u
	}
	return nil, &u
}
